const { exec,escape } = require('../db/mysql');
const xss = require("xss");

const getList = (author, keyword, tagName) => {
    // 这里的1=1 用来占位。如果不写，并且author keyword都没有值 后面直接拼接order... 会报错
    // 同样的原理还可以用在 url拼接参数
  // author = escape(author);
  // keyword = escape('');
  let sql = `select * from blogs where 1=1 `;

    if (author) {
        // 后面有空格
        sql += `and author=${author} `;
    }
    if (keyword) {
      // 仍执行
      sql += `and title like '%'${keyword}'%' `;
    }
    if (tagName) {
      sql += `and tag like '%${tagName}%'  `;
    }
    // 根据 cresteTime 倒序排序
    sql += `order by createtime desc;`;
  console.log('getList-sql', sql);
  // 返回的是promise
    return exec(sql)
};

const getDetail = (id) => {
    id = escape(id);
    let sql = `select * from blogs where id=${id} `;
    return exec(sql).then(rows => {
      return rows[0]
    });
};

const getListByTag = (tagName) => {
  let sql = `select * from blogs where 1=1 `;
  if (tagName) {
    sql += `and tag like '%${tagName}%' `
  }
  return exec(sql).then(rows => {
    return rows;
  }).catch(err => {
    console.log(new Error('从数据库中获取tag内容失败'));
  });
};

const newBlog = (blogData = {}) => {
    //blogData是一个博客对象，包含title content属性
  const title = xss(blogData.title);
  const content = JSON.stringify(xss(blogData.content));
  const author = xss(blogData.author);
  const abstract = xss(blogData.abstract);
  const tags = xss(blogData.tag);
  const createTime = Date.now();
  const browse = 0;
  const sql = `insert into blogs (title,content, createtime, author, list, tag, browse) 
  values ('${title}',${content},${createTime},'${author}', '${abstract}', '${tags}', '${browse}');`;
  return exec(sql).then(insertData => {
      return {
          id: insertData.insertId
      }
  }).catch(err => {
    res.json('newBLog 从数据库中获取数据失败',err);
  })
};

const updateBlog = (id, blogData ={}) => {
    // id就是要更新博客的id
    // blogData 是一个博客对象， 包含title content 属性
  id = escape(id);
    // return true;
    const title = xss(blogData.title);
    const content = xss(blogData.content);
    const tags = xss(blogData.tag);
    const list = xss(blogData.list);
    
    const sql = `
        update blogs set title='${title}',content='${content}, list='${list}', tag='${tags}' where id=${id}
    `;
    return exec(sql).then(updateData => {
        if(updateData.affectedRows > 0){
            return true
        }
        return false
    })
    
};

const delBlog = (id,author) => {
    // id就是要删除博客的 id
    // return true
    const sql = `delete from blogs where id='${id}' and author='${author}'`;
    return exec(sql).then(deleteData => {
        if (deleteData.affectedRows > 0) {
            return true
        }
        return false
    })
};

const addBrowseNum = async (blogId) => {
  // 获取当前 blog 访问次数
  const sql_getCurrentBrowseNum =  `select browse from blogs where id=${blogId}`;
  let currentBrowseNum = await exec(sql_getCurrentBrowseNum);
  currentBrowseNum = JSON.parse(JSON.stringify(currentBrowseNum))[0].browse;
  const sql_addBrowseNum = `update blogs set browse=${currentBrowseNum+1} where id=${blogId}`;
  try {
    const result = await exec(sql_addBrowseNum);
  } catch (err) {
    return err;
  }
  // 当前访问次数 +1
};

const searchByTitle = async (title) => {
  const sql = `select * from blogs where title like '%${title}%'`;
  console.log('===== blogList =====', sql);
  return await exec(sql);
};


module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog,
    addBrowseNum,
    searchByTitle
};